<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\App;
use \EasyWeChat\Kernel\Messages\Message;


/**
 * 微信回调入口控制器
 * @package App\Http\Controllers\Wechat
 */
class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     * @return string
     */
    public function serve()
    {
        Log::error('request arrived.');
        //注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        try {
            $app = \App\Services\EasyWechat::officialAccount();
            //文本消息
            $app->server->push(\App\Services\WechatHandler\TextMessageHandler::class, Message::TEXT);
            //图片消息
            $app->server->push(\App\Services\WechatHandler\ImageMessageHandler::class, Message::IMAGE);
            //音频消息
            $app->server->push(\App\Services\WechatHandler\VoiceMessageHandler::class, Message::VOICE);
            //视频消息
            $app->server->push(\App\Services\WechatHandler\VideoMessageHandler::class, Message::VIDEO);
            //小视频消息
            $app->server->push(\App\Services\WechatHandler\ShortVideoMessageHandler::class, Message::SHORT_VIDEO);
            //地理位置消息
            $app->server->push(\App\Services\WechatHandler\LocationMessageHandler::class, Message::LOCATION);
            //链接消息
            $app->server->push(\App\Services\WechatHandler\LinkMessageHandler::class, Message::LINK);
            //事件消息
            $app->server->push(\App\Services\WechatHandler\EventMessageHandler::class, Message::EVENT);

            $response = $app->server->serve();
            //触发微信发送消息事件
            \App\Jobs\WxmsgSendHandle::dispatch($response->getContent())->onQueue('low');
            //将响应输出
            $response->send();
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            //生产环境不报错
            if (App::environment('product')) {
                echo 'success';
            } else {
                throw new \Exception($e->getMessage());
            }
        }
    }
}
